package com.ccteam.fluidmusic.ui

import android.os.Bundle
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.LiveData
import androidx.navigation.NavController
import com.bumptech.glide.Glide
import com.ccteam.fluidmusic.NavNowPlayingDirections
import com.ccteam.fluidmusic.NavPlaylistDirections
import com.ccteam.fluidmusic.R
import com.ccteam.fluidmusic.databinding.ActivityMainBinding
import com.ccteam.fluidmusic.utils.setupWithNavController
import com.ccteam.shared.core.UserCore
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject

/**
 * 主Activity，展示主要音乐界面的活动
 */
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    @Inject lateinit var userCore: UserCore

    private lateinit var binding: ActivityMainBinding

    private val mainActivityViewModel by viewModels<MainActivityViewModel>()

    private var currentNavController: LiveData<NavController>? = null
    private val transientGraphIds = mutableListOf<Int>()

    /**
     * 存储需要全部显示底部播放栏的Fragment
     */
    private val fullBottomIds = mutableListOf(
        R.id.onlineMusicFragment, R.id.localMusicFragment,
        R.id.momentsFragment, R.id.meFragment
    )

    /**
     * 存储需要不显示底部播放栏的Fragment
     */
    private val noneBottomIds = mutableListOf(
        R.id.nowPlayingFragment, R.id.momentDetailFragment,
        R.id.loginFragment, R.id.loginVerificationFragment, R.id.registerFragment,
        R.id.forgetPasswordFragment
    )

    /**
     * 存储不需要处理底部播放栏的Fragment
     */
    private val dialogBottomIds = mutableListOf(
        R.id.playlistBottomSheetFragment, R.id.musicMoreBottomSheetFragment,
        R.id.localMusicMoreBottomSheetFragment, R.id.descriptionDialog,
        R.id.localMusicTagFragment, R.id.localMusicTagEditFragment,
        R.id.selectBitrateDialog, R.id.publishCommentFragment, R.id.replayListFragment,
        R.id.addPlaylistBottomSheetFragment
    )

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        savedInstanceState ?: setupBottomNavigationBar()

        binding.FluidMusicBottomBar.getPlayerBar().setOnClickListener {
            currentNavController?.value?.navigate(
                NavNowPlayingDirections.actionGlobalNowPlayingFragment()
            )
        }

        binding.FluidMusicBottomBar.getPlayPauseButton().setOnClickListener {
            mainActivityViewModel.playOrPause()
        }

        binding.FluidMusicBottomBar.getPlaylistButton().setOnClickListener {
            currentNavController?.value?.navigate(NavPlaylistDirections.actionGlobalPlaylistBottomSheet())
        }

        mainActivityViewModel.nowPlayingMediaData.observe(this, {
            it?.let {
                binding.FluidMusicBottomBar.getNowPlayingMediaSubtitle().text = getString(R.string.now_playing_subtitle,it.title,it.artist)
            } ?: return@observe
        })

        mainActivityViewModel.mediaButtonRes.observe(this, {
            binding.FluidMusicBottomBar.getPlayPauseButton().setIconResource(it)
        })

        mainActivityViewModel.mediaAlbumArt.observe(this, {
            Glide.with(this)
                .load(it.second)
                .placeholder(R.drawable.img_default_album)
                .into(binding.FluidMusicBottomBar.getAlbumArtImageView())
        })
    }

    override fun onRestoreInstanceState(savedInstanceState: Bundle) {
        super.onRestoreInstanceState(savedInstanceState)
        // BottomNavigationBar会恢复到初始状态
        // 而选中的item也会恢复到初始状态
        // 我们可以重新设置带导航的底部导航栏
        setupBottomNavigationBar()
    }

    /**
     * 设置多回退栈的底部导航栏，并加以目的地监听器
     * 以此实现在不同Fragment中隐藏或显示BottomNavigationBar的目的
     */
    private fun setupBottomNavigationBar(){
        val navGraphIds = listOf(
            R.navigation.nav_online_music,
            R.navigation.nav_local_music, R.navigation.nav_moments, R.navigation.nav_me
        )

        // 设置支持多回退栈的底部导航栏NavController
        val controller = binding.FluidMusicBottomBar.getBottomNavigationView().setupWithNavController(
                navGraphIds = navGraphIds,
                fragmentManager = supportFragmentManager,
                containerId = R.id.main_nav_host_container,
                intent = intent
        )

        controller.observe(this) { navController ->
            val graphId = navController.graph.id
            if (!transientGraphIds.contains(graphId)) {
                navController.addOnDestinationChangedListener(onDestinationChangedListener)
                transientGraphIds.add(graphId)
            }
        }
        currentNavController = controller
    }

    /**
     * 导航目的地监听，在不同目的地可能会进行不同的操作
     */
    private val onDestinationChangedListener = NavController.OnDestinationChangedListener {
            _, destination, _ ->
        when{
            fullBottomIds.contains(destination.id) ->{
                binding.FluidMusicBottomBar.performToFull()
            }
            // 如果是进入正在播放界面，则隐藏底部全部内容
            noneBottomIds.contains(destination.id) ->{
                binding.FluidMusicBottomBar.performToNone()
            }
            // 如果是进入弹窗式的内容，不进行任何操作动画
            dialogBottomIds.contains(destination.id) ->{
                return@OnDestinationChangedListener
            }
            else ->{
                binding.FluidMusicBottomBar.performToHalf()
            }
        }
    }

}

const val PARENT_ID_KEY = "fluidmusic-parentId"